//
//  TelFriendViewController.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/11/15.
//  Copyright © 2017年 hbjApple. All rights reserved.
//
//ContactsUI
#import "TelFriendViewController.h"

#import "JXTActionSheet.h"
#import "AddTelFriendCell.h"
#import "InviteTelFriendCell.h"
#import <AddressBook/AddressBook.h>
#import <MessageUI/MessageUI.h>
#import "FriendCustomAlertView.h"
#import "UIScrollView+EmptyDataSet.h"
#import <ContactsUI/ContactsUI.h>
#import <Contacts/Contacts.h>
#import <AddressBook/AddressBookDefines.h>
#import <AddressBook/ABRecord.h>
#import "MYXMyFriendModel.h"
#import "MYXchatCell.h"
#import "MYY_MessageViewModel.h"
#import "MYXfindmatchModel.h"

#define OffsetForEmptyData -25
static NSString *const kShareInvitePath   = @"tmpl/register.html";
static NSString *const MYXchatCellIdentifier = @"MYXchatCell";
@interface TelFriendViewController ()<UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIAlertViewDelegate,JXTActionSheetDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,CNContactViewControllerDelegate,CNContactPickerDelegate>{
    NSMutableArray *_MYXUserArrays;
    NSMutableArray *_telUserArrays;
    NSMutableArray *_allTelArrays;
}
@property(nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong) FriendCustomAlertView *customAlertView;
@property(nonatomic,strong)MYXHttpManager *MYXHttpMana;
@end

@implementation TelFriendViewController
-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _MYXUserArrays = [NSMutableArray array];
    _telUserArrays = [NSMutableArray array];
    _allTelArrays = [NSMutableArray array];
    self.MYXHttpMana =[[MYXHttpManager alloc]init];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:MYXchatCellIdentifier bundle:nil] forCellReuseIdentifier:MYXchatCellIdentifier];
    [self loadAddressBookData];
}
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, WIDTH, HEIGHT+20) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
    }
    return _tableView;
}
#pragma mark-- DZNEmptyDataSetSource
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"telfriend_no"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"暂时没有手机联系人哦";
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName : [UIFont boldSystemFontOfSize:14.0f],
                                 NSForegroundColorAttributeName : [UIColor lightGrayColor]
                                 };
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return OffsetForEmptyData;
}

#pragma mark - DZNEmptyDataSetDelegate

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}


#pragma mark - tableview datasource and delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;{
    return _MYXUserArrays.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MYXchatCell *MYXchatCe = (MYXchatCell *)[tableView dequeueReusableCellWithIdentifier:MYXchatCellIdentifier];
    MYXchatCe.selectionStyle = UITableViewCellSelectionStyleNone;
    MYXfindmatchModel *MYXfindmatchMo =_MYXUserArrays[indexPath.row];
    
    MYXchatCe.titileLabel.text = MYXfindmatchMo.username;
    if (MYXfindmatchMo.userface) {
        [MYXchatCe.ImageVie sd_setImageWithURL:[NSURL URLWithString:MYXfindmatchMo.userface] placeholderImage:[UIImage imageNamed:@"AppIcon"]];
        
    }else{
        MYXchatCe.ImageVie.image =[UIImage imageNamed:@"AppIcon"];
    }

    return MYXchatCe;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 71;
}


#pragma mark - AddressBook
- (void)loadAddressBookData{
    //这里有一个枚举类:CNEntityType,不过没关系，只有一个值:CNEntityTypeContacts
    switch ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts])
    {
            //存在权限
        case CNAuthorizationStatusAuthorized:
            //获取通讯录
            NSLog(@"存在权限");
            [self getmyAddressbook];
            
            break;
            
            //权限未知
        case CNAuthorizationStatusNotDetermined:
            //请求权限
            NSLog(@"权限未知");break;
            
            //如果没有权限
        case CNAuthorizationStatusRestricted:
        case CNAuthorizationStatusDenied://需要提示
           NSLog(@"如果没有权限");break;
    }
}

- (void)getmyAddressbook {

    NSMutableArray *telArrays = [NSMutableArray array];
    // 获取指定的字段,并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSLog(@"-------------------------------------------------------");
        //获取的联系人单一属性:First name
        CNPhoneNumber *phoneNumber;
        MYXMyFriendModel *friend = [[MYXMyFriendModel alloc] init];
        NSString *givenName = contact.givenName;
        NSString *familyName = contact.familyName;
        NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
        NSString *nameStr = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
        NSArray *phoneNumbers = contact.phoneNumbers;
       
        
        if (givenName) {
            if (familyName) {
                friend.friend_nickName =familyName;
            } else {
                friend.friend_nickName = givenName;
            }
        } else {
            if (familyName) {
                friend.friend_nickName = familyName;
            } else {
                friend.friend_nickName = [NSString stringWithFormat:@"未命名"];
            }
        }
         NSLog(@"friend.friend_nickName=%@", friend.friend_nickName);
        
        if ([friend.friend_nickName isEqualToString:@"未命名"]) {
            NSLog(@"这是拦截的账号哦");
        } else {
            for (CNLabeledValue *labelValue in phoneNumbers) {
                NSString *label = labelValue.label;
                phoneNumber = labelValue.value;
                NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);
                NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[]{}（#%-*+=_）\\|~(＜＞$%^&*)_+;"];
                NSString *tempString = [[phoneNumber.stringValue componentsSeparatedByCharactersInSet:doNotWant]componentsJoinedByString:@""];
                tempString = [tempString stringByReplacingOccurrencesOfString:@"86" withString:@""];
                [telArrays addObject:tempString];
                friend.friend_tel = tempString;
                friend.friend_name = tempString;
            }
            
          
            [_allTelArrays addObject:friend];

        }
       
        
    }];
    
    NSLog(@"mydict is ==== %@",telArrays);
    if (telArrays.count > 0) {
        [self compareTelData:telArrays];
    }
    
}



#pragma mark - Https data
- (void)compareTelData:(NSMutableArray *)tels{
    NSString *telStr = [tels componentsJoinedByString:@","];
    [self inifindmatchRequest:telStr];
}

-(void)inifindmatchRequest:(NSString *)ipones{
    [self.MYXHttpMana findmatch:ipones success:^(NSArray *findmatchListArray) {
        if (findmatchListArray.count>0) {
            [_MYXUserArrays addObjectsFromArray:findmatchListArray];
            [self.tableView reloadData];
        }
    } failure:^(NSString *errorCode) {
         [JXTHUDHelper showHUDText:errorCode type:@"error" inView:nil];
    } netDown:^{
         [JXTHUDHelper showHUDText:@"网络出错了～" type:@"error" inView:nil];
        
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
